package cn.zmit.kuxi.activity;

import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import cn.zmit.kuxi.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.StringUtils;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.IRequest;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.hardware.input.InputManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.zmit.kuxi.contants.Constants;
import cn.zmit.kuxi.contants.Response;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.request.CookieManager;
import cn.zmit.kuxi.request.RequestTask;

/** * @author @parameter * @return */
public class LoginActivity extends BaseActivity {
	@ViewInject(R.id.et_user_name)
	private EditText user_name;

	@ViewInject(R.id.et_user_pwd)
	private EditText user_pwd;

	@ViewInject(R.id.checkBox_remember_pwd)
	private CheckBox remember_pwd;

	@ViewInject(R.id.tv_forget_pwd)
	private TextView forget_pwd;

	@ViewInject(R.id.button_login)
	private Button login;

	@ViewInject(R.id.tv_registered)
	private TextView registered;

	@ViewInject(R.id.llRoot)
	private LinearLayout llroot;

	/**
	 * 登录手机号码
	 */
	private String phone;
	/**
	 * 登录密码
	 */
	private String password;
	/**
	 * 
	 * 以下是记住密码
	 */
	public static String YES = "yes";
	public static String NO = "no";
	private String isMemory = "";// isMemory变量用来判断SharedPreferences有没有数据，包括上面的YES和NO
	private String FILE = "saveUserNamePwd";// 用于保存SharedPreferences的文件
	private SharedPreferences sp = null;// 声明一个SharedPreferences

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		ViewUtils.inject(this);
		sp = getSharedPreferences(FILE, MODE_PRIVATE);
		isMemory = sp.getString("isMemory", NO);
		// 进入界面时，这个if用来判断SharedPreferences里面name和password有没有数据，
		// 有的话则直接打在EditText上面
		if (isMemory.equals(YES)) {
			phone = sp.getString("phone", "");
			password = sp.getString("password", "");
			user_name.setText(phone);
			user_pwd.setText(password);
		}
		Editor editor = sp.edit();
		editor.putString(phone, user_name.toString());
		editor.putString(password, user_pwd.toString());
		editor.commit();

		llroot.setOnTouchListener(new OnTouchListener() {

			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

				return inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
			}
		});
	}

	@OnClick({ R.id.button_login, R.id.tv_registered, R.id.tv_forget_pwd })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.button_login:
			if (checkForm()) {
				phone = user_name.getText().toString().trim();
				password = user_pwd.getText().toString().trim();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("phone", phone);
				map.put("password", password);
				RequestTask.getInstance().doLogin(this, map, new onRequestListener());
				remember();
			}

			break;
		case R.id.tv_registered:
			Bundle regist = new Bundle();
			regist.putString("flag", "register");
			openActivity(RegisteredActivity.class, regist);
			break;
		case R.id.tv_forget_pwd:
			Bundle regist2 = new Bundle();
			regist2.putString("flag", "forget");
			openActivity(ForgetPasswordActivity.class, regist2);

			break;

		default:
			break;
		}
	}

	// 请求
	private class onRequestListener extends OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response, DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);
			if (jsonData.optString(Response.CODE).equals("0")) {
				JsonData itemData = jsonData.optJson("user");
				String userId = itemData.optString("id");
				PreferenceHelper.write(context, SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, userId);
				openActivity(HomeActivity.class);
				ToastUtils.show(context, "登陆成功");
				finish();
			} else if (jsonData.optString(Response.CODE).equals("1")) {
				ToastUtils.show(context, jsonData.optString("message"));
			} else if (jsonData.optString(Response.CODE).equals("2")) {
				ToastUtils.show(context, jsonData.optString("message"));
			}else if (jsonData.optString(Response.CODE).equals("3")) {
				ToastUtils.show(context, jsonData.optString("message"));
			}
			// 保存cookie
			IRequest iRequest = (IRequest) request;
			HttpURLConnection connection = iRequest.getHttpURLConnection();
			CookieManager.getInstance().saveCookies(context, connection);
			// 设置已登陆
			PreferenceHelper.write(context, SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED, true);

		}
	}

	// 表单验证
	private Boolean checkForm() {
		phone = user_name.getText().toString().trim();
		password = user_pwd.getText().toString().trim();
		if (StringUtils.isEmpty(phone)) {
			ToastUtils.show(context, "手机号不能为空");
			return false;
		} else if (!StringUtils.isPhone(phone)) {
			ToastUtils.show(context, "请输入合法的手机号");
			return false;
		} else if (StringUtils.isEmpty(password)) {
			ToastUtils.show(context, "请输入密码");
			return false;
		}

		return true;
	}

	// remenber方法用于判断是否记住密码，
	// checkBox1选中时，提取出EditText里面的内容，
	// 放到SharedPreferences里面的name和password中
	private void remember() {
		if (remember_pwd.isChecked()) {
			if (sp == null) {
				sp = getSharedPreferences(FILE, MODE_PRIVATE);
			}
			Editor edit = sp.edit();
			edit.putString("phone", user_name.getText().toString().trim());
			edit.putString("password", user_pwd.getText().toString().trim());
			edit.putString("isMemory", YES);
			edit.commit();
		} else if (!remember_pwd.isChecked()) {
			if (sp == null) {
				sp = getSharedPreferences(FILE, MODE_PRIVATE);
			}
			Editor edit = sp.edit();
			edit.putString("isMemory", NO);
			edit.commit();
		}
	}

}
